//
//  DAMessageDetailFileUploadView.m
//  DAKnowledge
//
//  Created by DreamArts on 16/7/18.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DAMessageDetailFileUploadView.h"
#import "Masonry.h"
#import "DALabel.h"
#import "DAHeader.h"
#import "Utility.h"
#import "DAMessageDetailModel.h"
#import "UIImageView+WebCache.h"
#import "UAProgressView.h"
#import "DADownloadFile.h"

@interface DAMessageDetailFileUploadView (){
    UIImageView *userHeaderImageView; // 头像
    DALabel *userNameLabel;           // 用户名
    UILabel *timeline;                // 时间轴
    UIView *statusBackView;           // 时间轴状态的backView
    UIImageView *statusImageView;     // 时间轴状态的 imageView
    DALabel *timeLabel;               // 时间
    UIImageView *bookImageView;       // 文件的图片
    DALabel *fileNameLabel;           // 书名
    UIImageView *commentImageView;    // 右边评论的按钮图片
    UILabel *bottomLine;              // 底部线的label
    UIView *commentBackView;          // 评论按钮 点击的view (comment太小, 不好点击)
    UAProgressView *progressView;     // 进度条
    DALabel *fileSizeLabel;           // 文件大小label
    UILabel *middleLabel;             // 中间线的label
    DALabel *fileStatusLabel;         // 文件下载状态的label
}

@end
@implementation DAMessageDetailFileUploadView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor colorWithHexString:backGroundColor];
        // 头像
        userHeaderImageView = [[UIImageView alloc]init];
        userHeaderImageView.layer.cornerRadius = 5;
        [self addSubview:userHeaderImageView];
        
        UITapGestureRecognizer *userFaceTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickUserImage:)];
        userHeaderImageView.userInteractionEnabled = YES;
        [userHeaderImageView addGestureRecognizer:userFaceTap];
        
        // 用户名
        userNameLabel = [[DALabel alloc]init];
        userNameLabel.font = [UIFont systemFontOfSize:10];
        userNameLabel.textColor = [UIColor colorWithHexString:bookNameColor];
        [self addSubview:userNameLabel];
        // 时间轴
        timeline = [[UILabel alloc]init];
        timeline.backgroundColor = [UIColor colorWithHexString:timeLineColor];
        [self addSubview:timeline];
        // 时间轴状态的backView
        statusBackView = [[UIView alloc]init];
        statusBackView.backgroundColor = [UIColor colorWithHexString:@"#6EB8EC"];
        statusBackView.layer.cornerRadius = 10;
        [self addSubview:statusBackView];
        // 状态图片
        statusImageView = [[UIImageView alloc]init];
        statusImageView.image = [UIImage imageNamed:@"file_icon"];
        [statusBackView addSubview:statusImageView];
        // 时间
        timeLabel = [[DALabel alloc]init];
        timeLabel.font = [UIFont systemFontOfSize:12];
        timeLabel.textColor = [UIColor colorWithHexString:timeColor];
        [self addSubview:timeLabel];
        // 评论按钮的图片
        commentImageView = [[UIImageView alloc]init];
        commentImageView.image = [UIImage imageNamed:@"reply@3x"];
        [self addSubview:commentImageView];
        // 盖在评论按钮图上的view
        commentBackView = [[UIView alloc]init];
        [self addSubview:commentBackView];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickCommentImage:)];
        [commentBackView addGestureRecognizer:tap];
 
      
        // 文件名字
        fileNameLabel = [[DALabel alloc]init];
        fileNameLabel.font = [UIFont systemFontOfSize:13];
        [self addSubview:fileNameLabel];
        // 底部的线
        bottomLine = [[UILabel alloc]init];
        bottomLine.backgroundColor = [UIColor groupTableViewBackgroundColor];
        [self addSubview:bottomLine];
        
        // 进度条
        progressView = [[UAProgressView alloc]init];
        progressView.backgroundColor = [UIColor whiteColor];
        progressView.tintColor = [UIColor whiteColor];
        progressView.layer.cornerRadius = 26;
        [self addSubview:progressView];
        
        [progressView bringSubviewToFront:bookImageView];
        // 文件 image
        bookImageView = [[UIImageView alloc]init];
        [progressView addSubview:bookImageView];
        
        UITapGestureRecognizer *fileTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickFileImage:)];
        bookImageView.userInteractionEnabled = YES;
        [bookImageView addGestureRecognizer:fileTap];
        
        // 文件大小
        fileSizeLabel = [[DALabel alloc]init];
        fileSizeLabel.font = [UIFont systemFontOfSize:12];
        fileSizeLabel.textColor = [UIColor colorWithHexString:borrowTimeColor];
        [self addSubview:fileSizeLabel];
        
        // 中间分隔线
        middleLabel = [[UILabel alloc]init];
        middleLabel.backgroundColor = [UIColor lightGrayColor];
        [self addSubview:middleLabel];
        
        // 文件下载状态
        fileStatusLabel = [[DALabel alloc]init];
        fileStatusLabel.font = [UIFont systemFontOfSize:12];
        fileStatusLabel.textColor = [UIColor colorWithHexString:borrowTimeColor];
        [self addSubview:fileStatusLabel];
        
        
        
    }
    
    return self;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    // 页面布局
    [userHeaderImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(8);
        make.left.mas_equalTo(5);
        make.width.height.mas_equalTo(34);
    }];
    [userNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(userHeaderImageView.mas_bottom).offset(3);
        make.left.mas_equalTo(userHeaderImageView);
        make.right.mas_equalTo(timeline.mas_left).offset(-2);;
    }];
    
    [timeline mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.width.mas_equalTo(3);
        make.left.mas_equalTo(userHeaderImageView.mas_right).offset(20);
    }];
    [statusBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(15);
        make.left.mas_equalTo(userHeaderImageView.mas_right).offset(11);
        make.width.height.mas_equalTo(20);
    }];
    [statusImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(4);
        make.bottom.mas_equalTo(-4);
        make.left.mas_equalTo(5);
        make.right.mas_equalTo(-5);
    }];
    [timeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(15);
        make.left.mas_equalTo(statusImageView.mas_right).offset(8);
        make.right.mas_equalTo(-50);
    }];
    
    [commentImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(15);
        make.right.mas_equalTo(-8);
        make.width.mas_equalTo(18);
        make.height.mas_equalTo(12);
    }];
    
    [commentBackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(5);
        make.left.mas_equalTo(timeLabel.mas_right).offset(3);
        make.right.mas_equalTo(-5);
        make.height.mas_equalTo(25);
    }];
    
//    [bookImageView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(timeLabel.mas_bottom).offset(8);
//        make.left.mas_equalTo(statusBackView.mas_right).offset(8);
//        make.width.mas_equalTo(55);
//        make.height.mas_equalTo(55);
//    }];
    [progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(timeLabel.mas_bottom).offset(8);
        make.left.mas_equalTo(statusBackView.mas_right).offset(8);
        make.width.mas_equalTo(52);
        make.height.mas_equalTo(52);
    }];
    
    [bookImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.mas_equalTo(progressView).offset(3);
        make.right.bottom.mas_equalTo(progressView).offset(-3);
    }];
    
    [fileNameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(bookImageView);
        make.left.mas_equalTo(bookImageView.mas_right).offset(8);
        make.right.mas_equalTo(-20);
    }];
    
    [bottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(-1);
        make.left.mas_equalTo(0);
        make.right.mas_equalTo(0);
        make.height.mas_equalTo(1);
    }];
    
    [fileSizeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(fileNameLabel.mas_bottom).offset(8);
        make.left.mas_equalTo(fileNameLabel);
        make.width.mas_equalTo(45);
        make.height.mas_equalTo(20);
    }];
    
    [middleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(fileSizeLabel.mas_centerY);
        make.left.mas_equalTo(fileSizeLabel.mas_right).offset(0);
        make.width.mas_equalTo(1);
        make.height.mas_equalTo(10);
    }];
    
    [fileStatusLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(middleLabel.mas_right).offset(5);
        make.top.mas_equalTo(fileSizeLabel);
        make.right.mas_equalTo(self.mas_right).offset(-20);
        make.height.mas_equalTo(fileSizeLabel);
    }];
    
    
    
}
- (void)setModel:(DAMessageDetailModel *)model{
    _model = model;
    // 头像
    [userHeaderImageView sd_setImageWithURL:[NSURL URLWithString:model.userFace] placeholderImage:[UIImage imageNamed:@"holderface"] options:SDWebImageRefreshCached];
    // 用户名
    [userNameLabel setText:model.userName fitToContent:YES];
    // 时间 国际化
    NSString *string = NSLocalizedString(@"uploaded", nil);
    NSString *text = [NSString stringWithFormat:@"%@ %@", model.timelineDate, string];
    [timeLabel setText:text fitToContent:YES];
    NSString *file = [NSString stringWithFormat:@"file_%@.png", model.timelinefileExtend];
    UIImage *image = [UIImage imageNamed:file];
    bookImageView.image = image;
    // 文件名
    [fileNameLabel setText:model.timelineMessage fitToContent:YES];
    
    BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@", model.timelinefoldername, model.timelinefileExtend]];
    [self changeDownloadSatutsWithIsExist:isExist];
   
    fileSizeLabel.text = [self calculateTheFileSize:model.timelinefilesize];
    
    
    
}

#pragma mark - 根据本地文件是否存在 来改变文字状态
- (void)changeDownloadSatutsWithIsExist:(BOOL) isExist{
    NSString *downloadSuccessfulStr = NSLocalizedString(@"isDownloadingSuccessful", nil);
    NSString *notDownloadStr = NSLocalizedString(@"NotDownload", nil);
    if (isExist) {
        fileStatusLabel.text = downloadSuccessfulStr;
        fileStatusLabel.textColor = [UIColor supportGreenColor];
    }else{
        fileStatusLabel.text = notDownloadStr;
        fileStatusLabel.textColor = [UIColor colorWithHexString:borrowTimeColor];
    }
}

- (void)clickCommentImage:(UITapGestureRecognizer *)tap{
    [self.delegate clickMessageDetailFileUpload];
}
#pragma mark 点击文件图片
- (void)clickFileImage:(UITapGestureRecognizer *)tap{
    BOOL isExist = [self isFileExist:[NSString stringWithFormat:@"%@.%@", self.model.timelinefoldername, self.model.timelinefileExtend]];
    [self changeDownloadSatutsWithIsExist:isExist];
    
    if (isExist) {
        [self.delegate openFileWithUrl:self.model];
    }else{
        [DADownloadFile downloadFileWithPath:self.model.timelinefileurl fileFolderName:self.model.timelinefoldername FileExtend:self.model.timelinefileExtend block:^(CGFloat count) {
            [progressView setProgress:count];
            progressView.tintColor = [UIColor supportGreenColor];
        } commpleteBlock:^{
            progressView.tintColor = [UIColor whiteColor];
            NSString *str = NSLocalizedString(@"isDownloadingSuccessful", nil);
            fileStatusLabel.text = str;
            fileStatusLabel.textColor = [UIColor supportGreenColor];
        }];
    }

}

#pragma mark - 点击用户头像的时候方法
- (void)clickUserImage:(UITapGestureRecognizer *)tap{
    [self.delegate clickMessageDetailFileUploadUserFaceWithUserID:self.model.userID];
}

#pragma mark - 判断沙盒里是否有这个文件
-(BOOL)isFileExist:(NSString *)fileName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    //  NSLog(@"该文件：%@",result?@"有！！":@"不存在");
    return result;
}


#pragma mark - 计算文件大小
- (NSString *)calculateTheFileSize:(NSString *)size{
    int fileSize = size.intValue;
    NSString *strSize;
    float fileSizeK = 0.0;
    float fileSizeM = 0.0;
    if (fileSize > 999 && fileSize < 999 * 1024) {
        fileSizeK = fileSize / 1024.0;
        strSize = [NSString stringWithFormat:@"%.2fK", fileSizeK];
    }else if (fileSize >= 999 * 1024){
        fileSizeM = fileSize / (1024 * 1024);
        strSize = [NSString stringWithFormat:@"%.2fM", fileSizeM];
    }else{
        strSize = [NSString stringWithFormat:@"%dB", fileSize];
    }
    return strSize;
}

#pragma mark - 清除缓存时 发出的通知
- (void)changeAllStatus{
    NSString *notDownloadStr = NSLocalizedString(@"NotDownload", nil);
    fileStatusLabel.text = notDownloadStr;
    fileStatusLabel.textColor = [UIColor colorWithHexString:borrowTimeColor];
}



/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
